﻿
Namespace LightSwitchApplication

    Public Class PayPeriod
        Dim payPeriodStart As Date
        Dim payPeriodEnd As Date
        Dim payrollNumber As Integer


        Private Sub CreateNewPayPeriodMethod_Execute()
            Try
                Dim currentPayPeriod = From cpp In Me.DataWorkspace.ApplicationData.PayPeriod
                                               Where cpp.Status = 1
                With currentPayPeriod.FirstOrDefault
                    payPeriodStart = .StartDate
                    payPeriodEnd = .EndDate
                    payrollNumber = .Id
                End With
                If Not currentPayPeriod.FirstOrDefault.LastRunDateTime Is Nothing Then
                    If ShowMessageBox("Do you want to run this payroll again (This will delete current payroll items), proceed?", "Pay Period " & payPeriodStart.ToShortDateString & " - " & payPeriodEnd.Date.ToShortDateString, MessageBoxOption.YesNo) = Windows.MessageBoxResult.No Then
                        Exit Sub
                    Else
                        deleteCurrentPayRunRecords()
                    End If
                Else
                    If ShowMessageBox("Proceed with pay run " & payPeriodStart.ToShortDateString & " - " & payPeriodEnd.ToShortDateString, "Pay Period", MessageBoxOption.YesNo) = Windows.MessageBoxResult.No Then
                        Exit Sub
                    End If
                End If

                With currentPayPeriod.FirstOrDefault
                    .LastRunDateTime = Now
                    .LastRunBy = Application.Current.User.Name
                End With
                PayPeriod.Refresh()
                createPayrollItem(currentPayPeriod.FirstOrDefault)
            Catch ex As Exception
                ShowMessageBox("Payroll processing error")
                Me.Refresh()
            End Try

        End Sub

        Sub initialisePayrun()

        End Sub

        Sub createPayrollItem(payPeriod As PayPeriodItem)
            Dim activeEmployee = From activeEmp In Me.DataWorkspace.ApplicationData.Employee
                                 Where activeEmp.Status.ToUpper = "ACTIVE"

            For Each item In activeEmployee
                Dim newPayrollDetail = Me.DataWorkspace.ApplicationData.PayHistory.AddNew
                With newPayrollDetail
                    .PayPeriodItem = payPeriod
                    .EmployeeItem = item
                    .DateCreated = Now
                    .CreatedBy = Application.Current.User.Name
                End With
                ProcessDeductions(newPayrollDetail)
                ProcessAdditionalIncome(newPayrollDetail)
                Me.DataWorkspace.ApplicationData.SaveChanges()
            Next
        End Sub

        Sub ProcessAdditionalIncome(payHistory As PayHistoryItem)
            Dim income = From inc In Me.DataWorkspace.ApplicationData.CurrentPayrollIncomes
                         Where (CDate(inc.StartDate) <= CDate(payPeriodEnd) AndAlso CDate(inc.EndDate) >= CDate(payPeriodStart)) AndAlso
                         inc.EmployeeItem.EmployeeID = payHistory.EmployeeItem.EmployeeID

            For Each item In income
                Dim newIncome = Me.DataWorkspace.ApplicationData.PayHistoryMoreIncome.AddNew()
                With newIncome
                    .Amount = item.amount
                    .RefAdditionalIncomeItem = item.RefAdditionalIncomeItem
                    .PayHistoryItem = payHistory
                End With
                'Me.DataWorkspace.ApplicationData.SaveChanges()
            Next
        End Sub

        Sub ProcessDeductions(payHistory As PayHistoryItem)
            Dim deductions = From deduct In Me.DataWorkspace.ApplicationData.CurrentPayrollDeductionsSet
                             Where (CDate(deduct.StartDate) <= CDate(payPeriodEnd) AndAlso CDate(deduct.EndDate) >= CDate(payPeriodStart)) AndAlso
                             deduct.EmployeeItem.EmployeeID = payHistory.EmployeeItem.EmployeeID


            For Each item In deductions
                Dim newDeduction = Me.DataWorkspace.ApplicationData.PayHistoryMoreDeductions.AddNew()
                With newDeduction
                    .Amount = item.amount
                    .RefAdditionalDeductionItem = item.RefAdditionalDeductionItem
                    .PayHistoryItem = payHistory
                End With
                'Me.DataWorkspace.ApplicationData.SaveChanges()
            Next
        End Sub

        Sub ProcessLeaves(payHistory As PayHistoryItem)
            Dim filedLeaves = From fLeaves In Me.DataWorkspace.ApplicationData.LeaveHistories
                              Where fLeaves.EmployeeItem.EmployeeID = payHistory.EmployeeItem.EmployeeID AndAlso
                              ((CDate(fLeaves.EndDate) >= CDate(payHistory.PayPeriodItem.StartDate) AndAlso CDate(fLeaves.EndDate) <= CDate(payHistory.PayPeriodItem.EndDate)) OrElse
                               (CDate(fLeaves.StartDate) >= CDate(payHistory.PayPeriodItem.StartDate) AndAlso CDate(fLeaves.StartDate) <= CDate(payHistory.PayPeriodItem.EndDate)))


            For Each item As LeaveHistory In filedLeaves
                Dim computeStart As Date = Nothing
                Dim computeEnd As Date = Nothing
                Dim leaveDays As Integer = 0
                Dim leaveAmount As Decimal = 0
                Dim newLeave = Me.DataWorkspace.ApplicationData.PayHistoryLeavesSet.AddNew

                With newLeave
                    If item.Unit.ToUpper = "DAYS" Then
                        If item.StartDate < payHistory.PayPeriodItem.StartDate Then
                            computeStart = payHistory.PayPeriodItem.StartDate
                        Else
                            computeStart = item.StartDate
                        End If


                        If item.EndDate < payHistory.PayPeriodItem.EndDate Then
                            computeEnd = item.EndDate
                        Else
                            computeEnd = payHistory.PayPeriodItem.EndDate
                        End If

                        While computeStart <= computeEnd
                            If Not (computeStart.DayOfWeek = DayOfWeek.Saturday Or computeStart.DayOfWeek = DayOfWeek.Sunday) Then
                                leaveDays += 1
                            End If
                            computeStart += TimeSpan.FromDays(1)
                        End While
                        'Leave rate less Saturday and Sunday
                        leaveAmount = leaveDays * payHistory.EmployeeItem.DailyRate
                        .Number = leaveDays
                    Else
                        leaveAmount = item.Amount * (payHistory.EmployeeItem.DailyRate / LightPayConstants.workHoursPerDay)
                        .Number = item.Amount
                    End If

                    .LeaveType = item.LeaveType
                    .Unit = item.Unit
                    .Amount = leaveAmount
                End With
                

            Next
        End Sub


#Region "Delete current existing Payroll Items"
        Sub deleteCurrentPayRunRecords()
            deleteCurrentPayrunDeductions()
            deleteCurrentPayrunIncome()
            deleteCurrentPayrunLeave()
            deleteCurrentPayroll()
            'Me.DataWorkspace.ApplicationData.SaveChanges()
        End Sub
        Sub deleteCurrentPayrunDeductions()
            Dim currentDeductions = From currDed In Me.DataWorkspace.ApplicationData.PayHistoryMoreDeductions
                                     Where currDed.PayHistoryItem.PayPeriodItem.Id = payrollNumber

            For Each item As PayHistoryMoreDeduction In currentDeductions
                item.Delete()
            Next

        End Sub

        Sub deleteCurrentPayrunIncome()
            Dim currentIncome = From currInc In Me.DataWorkspace.ApplicationData.PayHistoryMoreIncome
                         Where currInc.PayHistoryItem.PayPeriodItem.Id = payrollNumber

            For Each item As PayHistoryMoreIncomeItem In currentIncome
                item.Delete()
            Next
        End Sub


        Sub deleteCurrentPayrunLeave()
            Dim currentLeave = From currLeave In Me.DataWorkspace.ApplicationData.PayHistoryLeavesSet
                               Where currLeave.PayHistoryItem.PayPeriodItem.Id = payrollNumber

            For Each item As PayHistoryLeaves In currentLeave
                item.Delete()
            Next
        End Sub
        Sub deleteCurrentPayroll()
            Dim currentPayrollItems = From currPayItems In Me.DataWorkspace.ApplicationData.PayHistory
                                      Where currPayItems.PayPeriodItem.Id = payrollNumber
            For Each item As PayHistoryItem In currentPayrollItems
                item.Delete()
            Next
        End Sub



#End Region
    End Class

End Namespace
